//
//  LBCategorySearchViewController.m
//  AFNetworking
//
//  Created by luckyRoy on 2018/1/30.
//

#import "LBCategorySearchViewController.h"
#import "LBFacListView.h"
#import "UIColor+LBColor.h"
#import "Masonry.h"
#import "LBCategorySearchBar.h"
#import "LBCategoryModel.h"
#import "LBCategoryMainView.h"
#import "LBToastView.h"

@interface LBCategorySearchViewController ()<UISearchBarDelegate>

@property (nonatomic, strong) LBCategorySearchBar *searchBar;

@property (nonatomic, strong) LBCategoryMainView *facCollectionView;

@property (nonatomic, strong) UIButton *confirmButton;

@property (nonatomic, strong) NSMutableArray *showlistArray;

@property (nonatomic, strong) NSMutableArray *defaultSelectedArray;

@property (nonatomic, copy) LBCategorySearchViewBlock choseBlock;

@property (nonatomic, weak) LBCategorySettingModel *settingModel;

@property (nonatomic, strong) NSMutableArray *totalArray;

@end

@implementation LBCategorySearchViewController

#pragma mark - life cycle

- (void)updateBySettingModel:(LBCategorySettingModel *)settingModel
                  choseBlock:(LBCategorySearchViewBlock)choseBlock
{
    self.settingModel = settingModel;
    self.choseBlock = choseBlock;
    self.totalArray = [NSMutableArray arrayWithArray:settingModel.currentShowArray];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    [self.navigationItem setHidesBackButton:YES];
    self.navigationController.navigationBar.backgroundColor = [UIColor blue];
    self.navigationItem.titleView = self.searchBar;
    [self.view addSubview:self.facCollectionView];
    [self.view addSubview:self.confirmButton];

    [self setUpUIFrame];
    
//    self.showlistArray = [NSMutableArray arrayWithArray:self.totalArray];
        
//    [self reloadListView];
    //默认隐藏
    [self.confirmButton setHidden:YES];
    
    [self.searchBar.searchBar becomeFirstResponder];
    
}

//- (void)reloadListView
//{
//    [self.facCollectionView reloadViewByNewListModels:[LBCategorySettingModel getListModelBySettingModel:self.settingModel currentPage:LBCategorySettingPageTypeSearchLevel]];
//}

- (void)reloadListViewWithModels:(NSMutableArray *)modelArray
{
    if (!self.settingModel.isSingleSelected) {
        if (modelArray.count) {
            [self.confirmButton setHidden:NO];
        } else {
            [self.confirmButton setHidden:YES];
        }
    }
    
    if (modelArray.count) {
        [self.facCollectionView lb_removeEmptyData];
    } else {
        [self.facCollectionView lb_setEmptyNoData:@"没有数据"];
    }
    
    if (!self.searchBar.searchBar.text.length) {
        [self.facCollectionView lb_removeEmptyData];
    }
    
    [self.facCollectionView reloadViewByNewListModels:@[modelArray]];
}

#pragma mark - setUpFrame

- (void)setUpUIFrame
{
    __block UIView *bottomView = nil;

    if (!self.settingModel.isSingleSelected) {
        //多选展示提交
        [self.confirmButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.bottom.right.equalTo(self.view);
            make.height.mas_equalTo(48);
        }];
        bottomView = self.confirmButton;
    }
    if (bottomView) {
        [self.facCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.left.right.equalTo(self.view);
            make.bottom.equalTo(bottomView.mas_top);
        }];
    } else {
        [self.facCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.left.right.equalTo(self.view);
            make.bottom.equalTo(self.view);
        }];
    }
}

#pragma mark - public

#pragma mark - private

- (void)buttonClick:(UIButton *)senter
{
    [self saveAndBackToLastPage];
}

- (void)saveAndBackToLastPage
{
    if (self.settingModel.searchPageSelectedModelArray.count) {
        if (self.choseBlock) {
            self.choseBlock(self.settingModel.searchPageSelectedModelArray);
        }
        [self.navigationController popViewControllerAnimated:YES];
    } else {
        [LBToastView showByMessage:@"至少选择一个分类"];
    }
}

#pragma mark - request

#pragma mark - setter

#pragma mark - getter

- (LBCategorySearchBar *)searchBar
{
    if (!_searchBar)
    {
        __weak __typeof(&*self)weakSelf = self;
        _searchBar = [[LBCategorySearchBar alloc] initWithFrame:CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width , 30)];
        _searchBar.searchBar.delegate = self;
        _searchBar.searchBar.placeholder = @"搜索分类名称";
        _searchBar.cancelBtnBlock = ^{
            
            [weakSelf.searchBar.searchBar resignFirstResponder];
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                [weakSelf.navigationController popViewControllerAnimated:YES];
            });
            
        };
        _searchBar.searchBar.returnKeyType = UIReturnKeyDone;
    }
    
    return _searchBar;
}

- (LBCategoryMainView *)facCollectionView
{
    if (!_facCollectionView) {
        __weak __typeof(&*self)weakSelf = self;
        LBCategoryMainViewLayout *viewLayout = [LBCategoryMainViewLayout new];
        viewLayout.isHideSectionView = YES;
        viewLayout.pageType = LBCategorySettingPageTypeSearchLevel;
        _facCollectionView = [[LBCategoryMainView alloc]initWithFrame:self.view.bounds settingModel:self.settingModel viewLayout:viewLayout complete:^(LBCategoryMainViewLayout *blockModel,NSMutableArray *selectedArry)
        {
            [weakSelf saveAndBackToLastPage];
            
        }];
    }
    return _facCollectionView;
}

- (UIButton *)confirmButton
{
    if (!_confirmButton) {
        _confirmButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_confirmButton setTitle:@"确定" forState:UIControlStateNormal];
        [_confirmButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _confirmButton.backgroundColor = [UIColor blue];
        _confirmButton.titleLabel.font = [UIFont systemFontOfSize:16];
        [_confirmButton addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _confirmButton;
}

#pragma mark -- UISearchBarDelegate --

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    [self closeSearchMode];
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    if ([searchText length]==0) {
        //如果输入为空，自动关闭搜索列表，展示全部服务器数据
        [self closeSearchMode];
    }
    else{
        //开始搜索
        [self enterSearchModeWithkeyword:searchText];
    }
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [self.searchBar.searchBar resignFirstResponder];
}

#pragma mark - search

//获取汉字拼音(传入汉字字符串, 返回小写拼音)
- (NSString *)getPinYin:(NSString *)aString
{
    //转成了可变字符串
    NSMutableString *str = [NSMutableString stringWithString:aString];
    //先转换为带声调的拼音
    CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformMandarinLatin,NO);
    //再转换为不带声调的拼音
    CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformStripDiacritics,NO);
    //转化为大写拼音
    NSString *pinYin = [str lowercaseString];
    
    //获取并返回，过滤所有空格符号
    return [pinYin stringByReplacingOccurrencesOfString:@" " withString:@""];
}

//进入搜索模式，展示搜索数据
- (void)enterSearchModeWithkeyword:(NSString *)keyword{
    NSMutableArray *results = [NSMutableArray new];
    
    if ([self checkIsChinese:keyword]) {
        //包含中文 只搜索中文
        for (LBCategoryModel *model in self.totalArray) {
            if ([model.name containsString:keyword]) {
                [results addObject:model];
            }
        }
    } else {
        for (LBCategoryModel *model in self.totalArray) {
            if ([[model.namePingYin lowercaseString] containsString:[self getPinYin:keyword]] ||
                [model.name containsString:keyword]) {
                [results addObject:model];
            }
        }
    }
    
    //给搜索结果数组赋值
    self.showlistArray = results;
    //回调搜索结果
//    [self.facCollectionView.collectionView lb_setEmptyNoData:@"无结果"];
    
    [self reloadListViewWithModels:self.showlistArray];
}

//退出搜索模式，展示全部远程数据
- (void)closeSearchMode{
    [self.searchBar resignFirstResponder];
    [self reloadListViewWithModels:[NSMutableArray array]];
}

/**
 *  @author zhengju, 16-06-29 10:06:05
 *
 *  @brief 检测字符串中是否含有中文，备注：中文代码范围0x4E00~0x9FA5，
 *
 *  @param string 传入检测到中文字符串
 *
 *  @return 是否含有中文，YES：有中文；NO：没有中文
 */
- (BOOL)checkIsChinese:(NSString *)string{
    for (int i=0; i<string.length; i++) {
        unichar ch = [string characterAtIndex:i];
        if (0x4E00 <= ch  && ch <= 0x9FA5) {
            return YES;
        }
    }
    return NO;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
